package com.ysd.service.util;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 时间工具类
 *
 * @author michael
 * @version 1.0.0
 * @date 2018-01-18
 */
public class DateTimeUtil {

    /**
     * 计算停车时长
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @return 停车时长字符串
     */
    public static String calculateTime(String startTime, String endTime) {

        LocalDateTime entranceTime;

        LocalDateTime exitTime;

        try {

            //****转换进出场时间
            entranceTime = LocalDateTime.parse(startTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            exitTime = LocalDateTime.parse(endTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

        }catch (Exception e){

            return "-";
        }

        //****时差
        Duration duration = Duration.between(entranceTime, exitTime);

        long days = duration.toDays();
        long hours = duration.toHours();
        long minutes = duration.toMinutes();
        long seconds = duration.getSeconds();

        if(days > 0){
            hours = hours % (days * 24);
        }

        if(hours > 0){
            minutes = minutes % (hours * 60);
        }

        if(minutes > 0){
            seconds = seconds % (minutes * 60);
        }

        return (days == 0 ? "" : (days + "天")) + (hours == 0 ? "" : (hours + "小时")) + (minutes == 0 ? "" : (minutes + "分")) + seconds + "秒";
    }

    public static String countDuration(long duration) {
        long day = duration / (60 * 60 * 24);
        long hour = duration / (60 * 60) - day * 24;
        long min = duration / 60 - hour * 60 - day * 24 * 60;
        long sec = duration - min * 60 - hour * 60 * 60 - day * 60 * 60 * 24;
        String totalTime = (day == 0 ? "" : (day + "天")) + (hour == 0 ? "" : (hour + "小时")) + (min == 0 ? "" : (min + "分")) + sec + "秒";
        return totalTime;
    }

}
